﻿using System.Collections.Generic;
using System.Linq;
using DreamStore.WebShop.Models;
using Orchard.ContentManagement;
using Orchard.Data;

namespace DreamStore.WebShop.Services
{
    public class CustomerDiscountService : ICustomerDiscountService
    {
        private readonly IRepository<CustomerDiscountProgramPartRecord> _customerDiscountProgramPartRecordRepository;
        private readonly IRepository<ContentCustomerDiscountProgramsRecord> _contentCustomerDiscountProgramsRecordRepository;

        public CustomerDiscountService(IRepository<CustomerDiscountProgramPartRecord> programRecordRepo, IRepository<ContentCustomerDiscountProgramsRecord> programsRecordRepo)
        {
            this._customerDiscountProgramPartRecordRepository = programRecordRepo;
            this._contentCustomerDiscountProgramsRecordRepository = programsRecordRepo;
        }

        public void UpdateCustomerDiscountsForContentItem(ContentItem item, IEnumerable<CustomerDiscountProgramEntry> discounts)
        {
            var record = item.As<CustomerDiscountsPart>().Record;
            var oldDiscounts = _contentCustomerDiscountProgramsRecordRepository.Fetch(
                r => r.CustomerDiscountsPartRecord == record);
            var lookupNew = discounts
                .Where(e => e.IsChecked)
                .Select(e => e.CustomerDiscountProgram)
                .ToDictionary(r => r, r => false);

            // Delete the discounts that are no longer there
            // and mark the ones that should stay
            foreach (var contentCustomerDiscountProgramsRecord in oldDiscounts)
            {
                if (lookupNew.ContainsKey(
                    contentCustomerDiscountProgramsRecord.CustomerDiscountProgramPartRecord))
                {

                    lookupNew[contentCustomerDiscountProgramsRecord.CustomerDiscountProgramPartRecord]
                        = true;
                }
                else
                {
                    _contentCustomerDiscountProgramsRecordRepository.Delete(contentCustomerDiscountProgramsRecord);
                }
            }

            // Add the new discounts
            foreach (var discount in lookupNew.Where(kvp => !kvp.Value)
                                           .Select(kvp => kvp.Key))
            {
                _contentCustomerDiscountProgramsRecordRepository.Create(new ContentCustomerDiscountProgramsRecord
                {
                    CustomerDiscountProgramPartRecord = discount,
                    CustomerDiscountsPartRecord = record
                });
            }
        }

        public IEnumerable<CustomerDiscountProgramPartRecord> GetCustomerDiscounts()
        {
            return _customerDiscountProgramPartRecordRepository.Table.ToList();
        }
    }
}